<?php
namespace App\Controller\App;

use App\Query\UserAddressQuery;
use App\Repository\UserAddressRepository;
use App\Request\UserAddressRequest;

class UserAddressController extends Controller
{
    // 我的地址
    protected function user()
    {
        return UserAddressQuery::user($this->auth());
    }
    
    // 我的地址
    public function index()
    {
        return $this->user()->get();
    }
    
    // 获取默认
    public function default()
    {
        return $this->user()->first();
    }
    
    // 创建
    public function create(UserAddressRequest $request)
    {
        if(UserAddressRepository::make()->create($this->auth(), $request->validated()))
        {
            $this->message('create');
        }
        
        $this->error('create');
    }
    
    // 修改
    public function update($id, UserAddressRequest $request)
    {
        $model = $this->user()->find($id);
        
        if($model && UserAddressRepository::make($model)->save($request->validated()))
        {
            $this->message('update');
        }
        
        $this->error('update');
    }
    
    // 删除
    public function delete($id)
    {
        $model = $this->user()->find($id);
        
        if($model && $model->delete())
        {
            $this->message('delete');
        }
        
        $this->error('delete');
    }
    
    // 设置为默认
    public function check($id)
    {
        $model = $this->user()->find($id);
        
        if($model && $model->touch())
        {
            $this->message('ok');
        }
        
        $this->error('error');
    }
}
